import { Button, Form, Input, Spin, message } from 'antd'
import { withRouter } from 'react-router-dom'
import { useState } from 'react'
import { signIn } from 'api'
import { setData } from 'utils/local'
import './style.css'
const { Item } = Form

function Login(props) {
  const [spin, setSpin] = useState(false)
  /* 本地验证通过后的进行登录请求 */
  const onFill = (ref) => {
    setSpin(true)
    signIn(ref.username, ref.password)
    .then(({ data }) => {
      setSpin(false)
      /* 登录的状态成功就保存token和用户信息 */
      if (data.state) {
        message.success(data.msg, 1.5)
        setData('token', data.token)
        setData('userInfo', data.userInfo)
        props.history.push('/')
      } else {
        message.error(data.msg, .8)
      }
    })
    .catch( () => {
      setSpin(false)
    })
      
  
    
  }

  return (
  <div className="login">
    <div className="login_wrap">
      <Spin spinning={spin} size="large">
      <h2 className="login_wrap_h2">Sign in to man`man</h2>
        <Form
          className="login_wrap_form"
          layout="vertical"
          onFinish={onFill}
          initialValues={{
            username: 'admin',
            password: 'admin'
          }}
        >
          <Item
            label="Username or email address"
            name="username"
            rules={[{ required: true }]}
          >
            <Input
              type="text"
              autoComplete="off"
              className="wrap_form_input"
            ></Input>
          </Item>

          <Item
            label="Password"
            name="password"
            rules={[
              { required: true }
            ]}
          >
            <Input
              type="password"
              autoComplete="off"
            ></Input>
          </Item>
  
          <Item>
            <Button
              className="login_wrap_form_button"
              type="link"
              htmlType="submit"
              >Sign in</Button>
          </Item>
        </Form>
      </Spin>
    </div>
  </div>
  )
}

export default withRouter(Login)